<!-- 用户注册解决方案：
    用户注册分为两步：1、上传用户头像，返回用户头像的 acatarUrl；
    2、将用户信息（用户名、密码、电话、角色、头像）提交到后端，后端将用户信息存储到数据库中。

    用户头像解决方案：用户上传头像（URL：.../avatar），后端拿到图片，将图片保存到文件夹中，
    成功后返回请求图片地址（avatarUrl = .../avatar/{图片名称(包括扩展名)}）。图片命名规则：GUID + 扩展名。

    用户获取头像解决方案：用户使用 avatarUrl 访问图片，后端拿到avatarUrl后解析获得图片名称，根据图片名称读取图片，返回图片。
-->
<template>
    <div class="container-login">
        <div class="container-login-item">
            <div>
                <div class="to-login" @click="router.go(-1)"><el-icon>
                        <ArrowLeftBold />
                    </el-icon></div>
                <div>
                    <el-form :model="form" :rules="rules" label-width="auto" class="demo-ruleForm login-box"
                        :size="formSize" status-icon>
                        <el-form-item class="login-item" v-if="imageSrc">
                            <div class="avatar-container">
                                <img :src="imageSrc" alt="">
                            </div>
                        </el-form-item>
                        <el-form-item class="login-item">
                            <input class="register-row" type="text" autocomplete="off" placeholder="请输入用户名"
                                maxlength="10" required v-model="form.userName" />
                        </el-form-item>
                        <el-form-item class="login-item">
                            <input class="register-row" autocomplete="off" placeholder="请输入密码" maxlength="10"
                                v-model="form.password" />
                        </el-form-item>
                        <el-form-item class="login-item">
                            <input class="register-row" autocomplete="off" placeholder="请输入电话" maxlength="11"
                                v-model="form.phone" />
                        </el-form-item>
                        <el-form-item class="login-item">
                            <input class="register-btn" type="button" :value="imageSrc ? '重新上传' : '上传头像'"
                                @click.stop="avatarUpload" />
                        </el-form-item>
                        <el-form-item class="login-item">
                            <input class="register-btn" type="button" @click="register()" value="注册" />
                        </el-form-item>
                    </el-form>
                </div>
            </div>
        </div>
        <avatarsCropper class="avatar-cropper" v-if="dialogVisibleCorpper"
            v-model:dialogVisibleCorpper="dialogVisibleCorpper" @getImagValue="getImag" />
    </div>
</template>

<script setup name="Register">
import { ref } from 'vue';
import service from '@/utils/request';
import { useRouter } from 'vue-router';
import avatarsCropper from './avatarCropper.vue';
const router = useRouter();
const dialogVisibleCorpper = ref(false);
const avatarImage = ref(null);
const imageSrc = ref(null);
const avatarData = ref(null);
const form = ref([{
    userName: '',
    password: '',
    phone: '',
    headImag: '',
}]);
// 获取用户头像
const getImag = (value) => {
    // 将base64格式的图片转换为file
    convertBase64ToFile(value);
};
const base64ToBlob = (base64, contentType) => {
    const byteCharacters = atob(base64);
    const byteNumbers = new Array(byteCharacters.length);
    for (let i = 0; i < byteCharacters.length; i++) {
        byteNumbers[i] = byteCharacters.charCodeAt(i);
    }
    const byteArray = new Uint8Array(byteNumbers);
    return new Blob([byteArray], { type: contentType });
};
const blobToFile = (blob, fileName) => {
    return new File([blob], fileName, { type: 'image/png' });
};
const convertBase64ToFile = (base64) => {
    const contentType = base64.split(',')[0].match(/:(.*?);/)[1];
    const base64Data = base64.split(',')[1];
    const blob = base64ToBlob(base64Data, contentType);
    avatarData.value = blobToFile(blob, 'image.png');
    imageSrc.value = URL.createObjectURL(avatarData.value);
};
const register = () => {
    if (!checkData()) {
        return;
    }
    const formData = new FormData();
    formData.append('file', avatarData.value);
    formData.append('userName', form.value.userName);
    formData.append('password', form.value.password);
    formData.append('phone', form.value.phone);
    service({
        url: 'api/Auth/register',
        method: 'post',
        data: formData,
    }).then(res => {
        if (res != undefined) {
            if (res.status == 200) {
                ElMessage({
                    message: '注册成功',
                    type: 'success',
                    plain: true,
                });
                router.push('/login');
            }
        }
    });
};
const checkData = () => {
    if (form.value.userName == undefined || form.value.password == undefined ||
        form.value.phone == undefined) {
        ElMessage({
            message: '请输入完整信息',
            type: 'error',
            plain: true,
        });
        return false;
    }
    if (form.value.userName.trim() == '') {
        ElMessage({
            message: '请输入用户名',
            type: 'error',
            plain: true,
        });
        return false;
    }
    if (form.value.password.trim() == '') {
        ElMessage({
            message: '请输入密码',
            type: 'error',
            plain: true,
        });
        return false;
    }
    if (form.value.phone.trim() == '') {
        ElMessage({
            message: '请输入手机号',
            type: 'error',
            plain: true,
        });
        return false;
    }
    if (avatarData.value == null || avatarData.value == '') {
        ElMessage({
            message: '请上传头像',
            type: 'error',
            plain: true,
        });
        return false;
    }
    return true;
};
const avatarUpload = () => {
    dialogVisibleCorpper.value = true;
}
</script>

<style scoped>
.container-login {
    margin: 0;
    padding: 0;
    width: 100vw;
    height: 100vh;
}

.container-login-item {
    display: block;
    width: 100%;
    height: 100%;
    align-content: center;
    background: url('@/assets/imag/P-C.jpg') no-repeat;
    background-size: 100% 100%;
}

.to-login {
    position: fixed;
    top: 12px;
    left: 20px;
    z-index: 1000;
    color: #444;
}

.login-box {
    margin: 0 10%;
    height: 60%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    margin-bottom: 20px;
}

.login-item {
    margin: 0;
    padding: 0;
    width: 100%;
}

.avatar-container {
    margin: 0 auto;
    padding: 0;
    width: 40%;
    Aspect-ratio: 1/1;
}

.avatar-container img {
    margin: 0;
    padding: 0;
    width: 100%;
    height: 100%;
    border-radius: 50%;
}

.register-row {
    margin: 10px auto;
    padding-left: 20px;
    width: 250px;
    height: 30px;
    border-radius: 10px;
    text-align: left;
    color: white;
    background-color: rgba(82, 91, 117, 0.6);
    border: 1px solid rgb(0 0 0);
    outline: none;
}

::placeholder {
    /* 设置 placeholder 属性的字体颜色 */
    color: white;
}

input:focus::placeholder {
    /* input标签获取焦点时隐藏 placeholder，失去焦点且没有文本时显示 */
    opacity: 0;
}

.register-btn {
    margin: 10px auto;
    width: 250px;
    height: 30px;
    border-radius: 10px;
    text-align: center;
    color: white;
    background-color: rgb(143 243 245);
    border: 1px solid rgb(143 243 245);
    outline: none;
    opacity: 0.9;
}

select>option {
    color: black;
    background-color: whitesmoke;
}

.avatar-cropper {
    z-index: 1000;
    float: left;
    width: 100wh;
    height: 100vh;
    position: fixed;
    top: 0;
    left: 0;
}
</style>